/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package scms;

import java.net.*;
import java.io.*;

/**
 * chat server class
 * @author pumped
 */
public class ChatServer extends ChatAbstract {

	private ServerSocket serverSocket;
	public ChatGui gui;

	/**
	 * constructor taking output gui
	 * @param gui
	 */
	public ChatServer(ChatGui gui) {
		int serverTimeout = 10000;
		this.gui = gui;
		try {
			serverSocket = new ServerSocket(port);
			serverSocket.setSoTimeout(serverTimeout);
		} catch (IOException e) {
			System.out.println("error occured");
			e.printStackTrace();
		}
	}

	/**
	 * main thread body
	 */
	public void run() {
		while (true) {
			try {
				System.out.println("waiting for client");
				//wait for client
				Socket server = serverSocket.accept();
				System.out.println("client Connected");
				gui.addMessage("Client Connected");
				recieve = new DataInputStream(server.getInputStream());
				send = new DataOutputStream(server.getOutputStream());
				send.writeUTF("Welcome to chat");

				String message;
				while (true) {
					message = recieve.readUTF();
					System.out.print(message);
					gui.addMessage(message);
					send.writeUTF(message);
				}

			} catch (IOException e) {
				System.out.println("wait timed out");
			}
		}
	}

	/**
	 * sends message to client
	 * @param message
	 */
	public void sendMessage(String message) {
		try {
			if (send != null) {
				send.writeUTF(message);
				gui.addMessage(message);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * close, kills socket and thread
	 */
	public void close() {
		try {
			serverSocket.close();
		} catch (IOException e) {
		}
		this.interrupt();
	}
}
